package cc.luoqiming.upload.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageUtil {

    Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    private static String DEFAULT_CUT_PREVFIX = "cut_";

    public void cutImage(File srcImg, OutputStream outputStream, Rectangle rectangle) {
        if (srcImg.exists()) {
            FileInputStream fileInputStream = null;
            ImageInputStream imageInputStream = null;
            try {
                fileInputStream = new FileInputStream(srcImg);
                String types = String.join(",", ImageIO.getReaderFormatNames());
//                String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("]", ",");
                String suffix = null;

                if (srcImg.getName().indexOf(".") > -1) {
                    suffix = srcImg.getName().substring(srcImg.getName().lastIndexOf(".") + 1);
                }

                if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()+",") < 0) {
                    logger.error("Sorry, the image suffix is illegal. the standard image suffix is {}." + types);
                    return ;
                }

                imageInputStream = ImageIO.createImageInputStream(fileInputStream);
                ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
                reader.setInput(imageInputStream,true);
                ImageReadParam param = reader.getDefaultReadParam();
                param.setSourceRegion(rectangle);
                BufferedImage bi = reader.read(0, param);
                ImageIO.write(bi, suffix, outputStream);
            } catch (Exception e) {
                logger.error("cut image error");
                e.printStackTrace();
            } finally {
                try {
                    if(fileInputStream != null) fileInputStream.close();
                    if(imageInputStream != null) imageInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            logger.warn("the src image is not exist.");
        }
    }

    public void cutImage(File srcImg, OutputStream output, int x, int y, int width, int height){
        cutImage(srcImg, output, new java.awt.Rectangle(x, y, width, height));
    }

    public void cutImage(File srcImg, String destImgPath, java.awt.Rectangle rect){
        File destImg = new File(destImgPath);
        if(destImg.exists()){
            String p = destImg.getPath();
            try {
                if(!destImg.isDirectory()) p = destImg.getParent();
                if(!p.endsWith(File.separator)) p = p + File.separator;
                cutImage(srcImg, new java.io.FileOutputStream(p + DEFAULT_CUT_PREVFIX + "_" + new java.util.Date().getTime() + "_" + srcImg.getName()), rect);
            } catch (FileNotFoundException e) {
                logger.warn("the dest image is not exist.");
            }
        }else logger.warn("the dest image folder is not exist.");
    }

    public void cutImage(File srcImg, String destImg, int x, int y, int width, int height){
        cutImage(srcImg, destImg, new java.awt.Rectangle(x, y, width, height));
    }

    public void cutImage(String srcImg, String destImg, int x, int y, int width, int height){
        cutImage(new File(srcImg), destImg, new java.awt.Rectangle(x, y, width, height));
    }

    public void cutImage(String srcImg, String destImg, int x, int y, int width, int height, OutputStream outputStream){
        cutImage(new File(srcImg), destImg, new java.awt.Rectangle(x, y, width, height));
    }

}
